package controllers;

import play.*;
import play.mvc.*;

import java.util.*;

import models.*;

public class Login extends Controller {

	public static void emailExistsJSON() {
		String email = params.get("e");
		renderJSON(User.emailExists(email));
	}
	
	public static void connectJSON() {
		logout();
		String username = params.get("u");
		String password = params.get("p");
		User u = User.connect(username, password);
		if (u == null) {
			renderJSON(false);
		} else {
			login(u);
			renderJSON(u, new UserSerializer());
		}
	}
	
	public static void getCurrentUserJSON() {
		User u = getCurrentUser();
		if (u == null) {
			renderJSON(false);
		} else {
			renderJSON(u, new UserSerializer());
		}
	}
	
	public static void logoutJSON() {
		logout();
	}
	
	public static User getCurrentUser() {
		if (isLoggedIn()) {
			//System.out.println(""+Long.valueOf(session.get("uid")));
			User u = User.find("byId", Long.valueOf(session.get("uid"))).first();
			if(u != null) {
				return u;
			}
		}
		return null;
	}
	
	public static boolean isLoggedIn() {
		if (session.contains("loggedin")) {
			if (session.get("loggedin").equals("true")) {
				return true;
			}
		}
		return false;
	}
	
	private static void login(User u) {
		session.put("uid", ""+u.id);
		session.put("loggedin", "true");
	}
	
	private static void logout() {
		session.clear();
	}
    
}

